from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from apps.goods.models import SKU, GoodsCategory, SPU, SPUSpecification, SKUSpecification, SpecificationOption

class SKUSpecsModelSerializer(ModelSerializer):
    """商品sku规格"""
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

    class Meta:
        model=SKUSpecification
        fields = ['spec_id','option_id']

from django.db import transaction
class SKUModelSerializer(ModelSerializer):
    """SKU表数据序列化器"""
    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()
    spu = serializers.StringRelatedField(read_only=True)
    category = serializers.StringRelatedField(read_only=True)
    specs = SKUSpecsModelSerializer(many=True)
    class Meta:
        model=SKU
        fields = "__all__"

    def create(self, validated_data):
        # 使用事务保存sku
        specs = validated_data.pop('specs')
        with transaction.atomic():
            start_point = transaction.savepoint()
            try:
                sku = SKU.objects.create(**validated_data)
                for spec in specs:
                    SKUSpecification.objects.create(sku=sku,**spec)
            except:
                transaction.savepoint_rollback(start_point)
            else:
                transaction.savepoint_commit(start_point)
        return sku

    def update(self, instance, validated_data):
        # 修改sku表数据
        specs = validated_data.pop('specs')

        super().update(instance,validated_data)

        # 更新specs
        for spec in specs:
            #  spec = {spec_id: "4", option_id: 8}
            SKUSpecification.objects.filter(sku=instance,spec_id=spec.get('spec_id')).update(option_id=spec.get('option_id'))

        return instance


class SKUCategorySerializer(ModelSerializer):
    """三级分类信息"""
    class Meta:
        model=GoodsCategory
        fields = "__all__"


class SPUModelSerializer(ModelSerializer):
    """SPU表展示"""
    class Meta:
        model = SPU
        fields = "__all__"



class OptionModelSerializer(ModelSerializer):
    """规格选项"""
    class Meta:
        model=SpecificationOption
        fields=['id','value']



class GoodsSpecsModelSerializer(ModelSerializer):
    """规格"""
    options = OptionModelSerializer(many=True)
    class Meta:
        model=SPUSpecification
        fields = ['id','name','options']